package com.jieshuibao.service.handler;

import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.jieshuibao.model.db.WxUser;
import com.jieshuibao.service.CoreService;
import com.jieshuibao.service.WxUserService;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * 用户关注公众号Handler
 * <p>
 * Created by FirenzesEagle on 2016/7/27 0027. Email:liumingbo2008@gmail.com
 */
@Component
public class SubscribeHandler extends AbstractHandler {

	@Autowired
	@Qualifier("wxMpConfigStorage")
	protected WxMpConfigStorage configStorage;
	@Autowired
	@Qualifier("wxMpService")
	protected WxMpService wxMpService;
	@Autowired
	protected CoreService coreService;

	@Resource
	private WxUserService wxUserService;

	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
			Map<String, Object> context, WxMpService wxMpService,
			WxSessionManager sessionManager) throws WxErrorException {
		WxMpUser wxMpUser = coreService.getUserInfo(wxMessage.getFromUser(),
				"zh_CN");
		if (wxMpUser != null) {
			String openId = wxMpUser.getOpenId();
			String city = wxMpUser.getCity();
			String country = wxMpUser.getCountry();
			String headImgUrl = wxMpUser.getHeadImgUrl();
			String nickname = wxMpUser.getNickname();
			String province = wxMpUser.getProvince();
			String sex = wxMpUser.getSex();
			//Long subscribeTime = wxMpUser.getSubscribeTime();
			String unionId = wxMpUser.getUnionId();
			WxUser user = new WxUser();
			user.setOpenid(openId);
			user.setCity(city);
			user.setCountry(country);
			user.setHeadimgurl(headImgUrl);
			user.setNickname(nickname);
			user.setProvince(province);
			user.setSex(sex);
			user.setUnionid(unionId);

			WxUser wxUser = wxUserService.getWxUserByOpenid(openId);
			if (wxUser == null) {
				user.setCreateTime(new Date());
				// 首次关注
				wxUserService.addWxUser(user);
			} else {
				// 以前关注过
				wxUserService.updateWxUser(user);
			}
		} else {
			logger.info("进入subscribeMessageHandler" + wxMpUser + "未获取用户信息");
		}

		// TODO(user) 在这里可以进行用户关注时对业务系统的相关操作（比如新增用户）
		logger.info("进入subscribeMessageHandler" + wxMpUser.getNickname());
		WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT()
				.content("尊敬的" + wxMpUser.getNickname() + "，您好！")
				.fromUser(wxMessage.getToUser())
				.toUser(wxMessage.getFromUser()).build();
		logger.info("subscribeMessageHandler" + m.getContent());
		return m;
	}
};
